﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using SilverAmp.Shared;

namespace SilverAmp.Converters
{
    public class ExtensionTypeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is ISilverAmpExtension)
            {
                ISilverAmpExtension extension = value as ISilverAmpExtension;

                if (value == null) return null;
                if (!extension.IsVisibleInMenu) return Visibility.Collapsed;

                Type t = extension.GetType();
                //var q = t.GetCustomAttributes(true);
                var attrib =
                    (SilverAmpExportExtensionAttribute)Attribute.GetCustomAttribute(t,
                                                    typeof(SilverAmpExportExtensionAttribute));
                if (attrib == null) return Visibility.Collapsed;
                if (attrib.Type == (ExtensionType)Enum.Parse(typeof(ExtensionType), parameter.ToString(), true))
                    return Visibility.Visible;
                return Visibility.Collapsed;
            }
            if(value is IList<ISilverAmpExtension>)
            {

                IList<ISilverAmpExtension> extensions = (IList<ISilverAmpExtension>) value;
                List<ISilverAmpExtension> validExtension = new List<ISilverAmpExtension>();
                foreach (var extension in extensions)
                {

                    Type t = extension.GetType();

                    var attrib =
                        (SilverAmpExportExtensionAttribute) Attribute.GetCustomAttribute(t,
                                                                                         typeof (
                                                                                             SilverAmpExportExtensionAttribute
                                                                                             ));                   
                    if (attrib.Type == (ExtensionType) Enum.Parse(typeof (ExtensionType), parameter.ToString(), true))
                        validExtension.Add(extension);
                }
                return validExtension;

            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}